package com.naizhuai.ui.management;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.naizhuai.R;
import com.naizhuai.network.exception.ApiException;
import com.naizhuai.network.exception.ServerException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.adapter.ChosenChargeJoinAdapterHolder;
import com.naizhuai.ui.adapter.management.AddTeamAdapterHolder;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.ui.components.CircleImageView;
import com.naizhuai.ui.entity.management.CompanyBean;
import com.naizhuai.ui.entity.management.ManagementMainMsgBean;
import com.naizhuai.ui.entity.management.PersonUserEditBean;
import com.naizhuai.ui.management.presenter.CompanyManageDataApiStoreIml;
import com.naizhuai.ui.mianbusiness.setting.UserListChosenActivity;
import com.naizhuai.ui.mianbusiness.target.TargetCreateActivity;
import com.naizhuai.util.CheckEntityByDialogUtils;
import com.naizhuai.util.ConstantsPersonResources;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.ImageUtils;
import com.naizhuai.util.IntentUtils;
import com.naizhuai.util.ListUtils;
import com.naizhuai.util.NaizhuAILog;
import com.naizhuai.util.SearchPersonByDialogUtils;
import com.naizhuai.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observer;
import rx.Subscription;

/**
 * 公司添加小组页面
 */
public class CompanyAddPartActivity extends BaseActivity implements View.OnClickListener, AddTeamAdapterHolder.OnItemClickListener {
    private static final String TAG = "CompanyAddPartActivity";

    public static final int ADD_MANAGERS_CODE = 1000;
    public static final int ADD_MEMBER_CODE = 1001;
    public static final int ADD_MEMBER_MAIN = 1002;
    public static final int CLICK_OPERATE_CODE = 1003;

    @BindView(R.id.team_name_input)
    EditText departNameInput;

    @BindView(R.id.add_team_manage_list)
    RecyclerView addManageList;

    @BindView(R.id.add_team_normal_list)
    RecyclerView addNormalList;

    private List<PersonUserBean> managerList;
    private List<PersonUserBean> memberList;
    private AddTeamAdapterHolder manageAdapter;
    private AddTeamAdapterHolder memberAdapter;

    //添加主管理员
    @BindView(R.id.main_manager_thumb)
    CircleImageView managerThumb;
    @BindView(R.id.main_manager_name)
    TextView managerName;
    private PersonUserBean mainManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        managerList = new ArrayList<>();
        memberList = new ArrayList<>();
        initView();
    }

    private void initView() {
        setManageRecyclerViews();
    }

    private void setManageRecyclerViews() {
        //添加管理人员的list
        manageAdapter = new AddTeamAdapterHolder(this, managerList, AddTeamAdapterHolder.LIST_TYPE_MANAGE);
        addManageList.setHasFixedSize(true);
        addManageList.setNestedScrollingEnabled(false);
        addManageList.setLayoutManager(new LinearLayoutManager(this));
        addManageList.setItemAnimator(new DefaultItemAnimator());
        addManageList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        addManageList.setAdapter(manageAdapter);
        manageAdapter.setOnItemClickListener(this);

        //添加普通成员的list
        memberAdapter = new AddTeamAdapterHolder(this, memberList, AddTeamAdapterHolder.LIST_TYPE_MEMBER);
        addNormalList.setHasFixedSize(true);
        addNormalList.setNestedScrollingEnabled(false);
        addNormalList.setLayoutManager(new LinearLayoutManager(this));
        addNormalList.setItemAnimator(new DefaultItemAnimator());
        addNormalList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        addNormalList.setAdapter(memberAdapter);
        memberAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        List<PersonUserBean> users = (List<PersonUserBean>) data.getSerializableExtra(UserListChosenActivity.JOIN_PERSON_KEY);
        List<PersonUserBean> diffBean;
        switch (requestCode) {
            case ADD_MANAGERS_CODE:
                diffBean = ListUtils.getListsDifferData(managerList, users);
                diffBean = ListUtils.getListsDifferData(memberList, diffBean);
                diffBean = ListUtils.removeElement(diffBean, mainManager);
                managerList.addAll(diffBean);
                manageAdapter.notifyDataSetChanged();
                break;
            case ADD_MEMBER_CODE:
                diffBean = ListUtils.getListsDifferData(memberList, users);
                diffBean = ListUtils.getListsDifferData(managerList, diffBean);
                diffBean = ListUtils.removeElement(diffBean, mainManager);
                memberList.addAll(diffBean);
                memberAdapter.notifyDataSetChanged();
                break;
            case ADD_MEMBER_MAIN:
                mainManager = (PersonUserBean) data.getSerializableExtra(TargetCreateActivity.CHARGE_KEY);
                if (ListUtils.contain(memberList, mainManager) || ListUtils.contain(managerList, mainManager)) {
                    DialogUtils.showPromptDialog(this, getString(R.string.chosen_main_manage_error));
                    return;
                }
                ImageUtils.glideThumbViewByUrl(this, managerThumb, mainManager.getUserLogoUrl());
                managerName.setText(mainManager.getNickName());
                break;
            case CLICK_OPERATE_CODE:
                operateData(resultCode, data);
                break;
        }
    }

    private void operateData(int resultCode, Intent data) {
        PersonUserEditBean bean = (PersonUserEditBean) data.getSerializableExtra(PersonUserBean.USER_KEY);
        switch (resultCode) {
            case CompanyUseOperatActivity.RESULT_SAVE:
                if (bean.hasChangeDepartmentPower()) {
                    if (bean.getBeDepartPowerCode().equalsIgnoreCase(ConstantsState.DEPARTMENT_VICE_MANAGER_POWER)) {
                        managerList = ListUtils.removeElement(managerList, bean.getPersonBean());
                        memberList.add(bean.getPersonBean());
                    } else {
                        memberList = ListUtils.removeElement(memberList, bean.getPersonBean());
                        managerList.add(bean.getPersonBean());
                    }
                    manageAdapter.notifyDataSetChanged();
                    memberAdapter.notifyDataSetChanged();
                }
                break;
            case CompanyUseOperatActivity.RESULT_DELETE_FROM_DEPARTMENT:
                if (bean.getBeDepartPowerCode().equalsIgnoreCase(ConstantsState.DEPARTMENT_VICE_MANAGER_POWER)) {
                    managerList = ListUtils.removeElement(managerList, bean.getPersonBean());
                    manageAdapter.notifyDataSetChanged();
                } else {
                    memberList = ListUtils.removeElement(memberList, bean.getPersonBean());
                    memberAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    //    new AddTeamAdapterHolder.OnItemClickListener() {
//        @Override
//        public void onItemClick(View view, int position, int listIndex) {
//            NaizhuAILog.e("position="+position+";listIndex="+listIndex);
//            switch (listIndex){
//                case 0://管理类的列表集合
//                    operationSwitchAction(view,position);
//                    break;
//                case 1://管理人员的列表集合
//                    deleteUserListDialog(AddTeamAdapterHolder.LIST_TYPE_MANAGE,position);
//                    break;
//                case 2://普通成员的列表集合
//                    deleteUserListDialog(AddTeamAdapterHolder.LIST_TYPE_MEMBER,position);
//                    break;
//            }
//        }
//    }

//    private void deleteUserListDialog(int type,int position) {
//        String[] userActions = getResources().getStringArray(R.array.remove_user);
//        DialogUtils.showMultiDialog(this, null, new String[]{userActions[0]}, new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                switch (which){
//                    case 0:
//                        adapter.removeData(type,position);
//                        break;
//                }
//            }
//        });
//    }


//    private void requestOddPerson(int type,Context mContext) {
//        Observer<ManagementMainMsgBean> observer = new Observer<ManagementMainMsgBean>() {
//            @Override
//            public void onCompleted() {
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                if (e instanceof ServerException) {
//                    ServerException server = (ServerException) e;
//                    DialogUtils.showPromptDialog(mContext,server.getMsg());
//                }
//                DialogUtils.showPromptDialog(mContext,e.getMessage());
//            }
//
//            @Override
//            public void onNext(ManagementMainMsgBean result) {
//                int limitNumber;
//                String tagStr;
//                if(type==ADD_MANAGER_USER){
//                    tagStr=getResources().getText(R.string.manager_total).toString();
//                    limitNumber=2;
//                }else{
//                    tagStr=getResources().getText(R.string.normal_person).toString();
//                    limitNumber=Integer.MAX_VALUE;
//                }
//                CheckEntityByDialogUtils<PersonUserBean> checkUtils=new CheckEntityByDialogUtils<>(mContext, result.getNoOrganizationList(), limitNumber, tagStr, new CheckEntityByDialogUtils.AddPersonListener<PersonUserBean>() {
//                    @Override
//                    public void onClick(List<PersonUserBean> user) {
//                        int insertType;
//                        user=ListUtils.removeElement(user,mainManager);
//                        if(type==ADD_MANAGER_USER){
//                            insertType=AddTeamAdapterHolder.LIST_TYPE_MANAGE;
//                            user=ListUtils.getListsDifferData(memberList,user);
//                        }else{
//                            insertType=AddTeamAdapterHolder.LIST_TYPE_MEMBER;
//                            user=ListUtils.getListsDifferData(managerList,user);
//                        }
//                        adapter.insertDataList(insertType,user);
//                    }
//                });
//                checkUtils.initView();
//            }
//        };
//        CompanyManageDataApiStoreIml.getInstance().getCompanyMainMsgByIds(SharedPreferenceUtil.getInstance(this).getValue( CompanyBean.COMPANY_ID_KEY,"0")).subscribe(observer);
//    }


//    private void operationSwitchAction(View view, int position) {
//        int type=-1;
//        switch (position){
//            case 1:
//                choseMainManager(view,this);
//                break;
//            case 3:
//                type=ADD_MANAGER_USER;
//                break;
//            case 4:
//                type=ADD_NORMAL_USER;
//                break;
//        }
//        if(type!=-1)
//            requestOddPerson(type,this);
//    }
//
//    private void choseMainManager(View view, Context mContext) {
//        TextView tvMainManager= (TextView) view;
//        String[] userActions = getResources().getStringArray(R.array.chose_type);
//        DialogUtils.showMultiDialog(this, null, userActions, new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                int inputType=-1;
//                switch (which){
//                    case 0://电话查询
//                        inputType=SearchPersonByDialogUtils.INPUT_PHONE_TYPE;
//                        break;
//                    case 1://名字查询
//                        inputType=SearchPersonByDialogUtils.INPUT_NAME_TYPE;
//                        break;
//                    case 2://从没有加入部门的人中进行选择
//                        inputType=-1;
//                        break;
//                }
//                if(inputType!=-1){
//                    SearchPersonByDialogUtils searchUser=new SearchPersonByDialogUtils(mContext, inputType, new SearchPersonByDialogUtils.AddPersonListener() {
//                        @Override
//                        public void onClick(PersonUserBean user) {
//                            if(ListUtils.contain(memberList,user)||ListUtils.contain(managerList,user)){
//                                shortToast(getText(R.string.user_has_added).toString());
//                            }else{
//                                mainManager=user;
//                                tvMainManager.setText(String.format("%s@%s", user.getName(), user.getPhoneNumber()));
//                            }
//                        }
//                    });
//                    searchUser.initView();
//                }else{
//                    chosePersonInOdd(CompanyAddPartActivity.this,tvMainManager);
//                }
//
//            }
//        });
//    }

//    private void chosePersonInOdd(Context mContext,TextView tvMainManager) {
//        Observer<ManagementMainMsgBean> observer = new Observer<ManagementMainMsgBean>() {
//            @Override
//            public void onCompleted() {
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                if (e instanceof ServerException) {
//                    ServerException server = (ServerException) e;
//                    DialogUtils.showPromptDialog(mContext,server.getMsg());
//                }
//                DialogUtils.showPromptDialog(mContext,e.getMessage());
//            }
//
//            @Override
//            public void onNext(ManagementMainMsgBean result) {
//                String tagStr;
//                tagStr=getResources().getText(R.string.main_manager_total).toString();
//                CheckEntityByDialogUtils<PersonUserBean> checkUtils=new CheckEntityByDialogUtils<>(mContext, result.getNoOrganizationList(), 1, tagStr, new CheckEntityByDialogUtils.AddPersonListener<PersonUserBean>() {
//                    @Override
//                    public void onClick(List<PersonUserBean> user) {
//                        PersonUserBean person=user.get(0);
//                        if(ListUtils.contain(memberList,person)||ListUtils.contain(managerList,person)){
//                            shortToast(getText(R.string.user_has_added).toString());
//                        }else{
//                            mainManager=person;
//                            tvMainManager.setText(String.format("%s@%s", person.getName(), person.getPhoneNumber()));
//                        }
//                    }
//                });
//                checkUtils.initView();
//            }
//        };
//        CompanyManageDataApiStoreIml.getInstance().getCompanyMainMsgByIds(SharedPreferenceUtil.getInstance(this).getValue( CompanyBean.COMPANY_ID_KEY,"0")).subscribe(observer);
//    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_department_layout;
    }


    @OnClick({R.id.back_icon, R.id.add_manage_member, R.id.add_normal_member, R.id.add_finished_button, R.id.chosen_main_manager})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_icon:
                onBackPressed();
                break;

            case R.id.add_manage_member:
                //添加管理人员
                IntentUtils.startActivityWithStringForResult(new String[]{ChosenChargeJoinAdapterHolder.ENTER_TYPE_KEY},
                        new int[]{ChosenChargeJoinAdapterHolder.TYPE_ADD_PERSON_MANAGE}, this, UserListChosenActivity.class, ADD_MANAGERS_CODE);
                break;

            case R.id.add_normal_member:
                //添加其他成员
                IntentUtils.startActivityWithStringForResult(new String[]{ChosenChargeJoinAdapterHolder.ENTER_TYPE_KEY},
                        new int[]{ChosenChargeJoinAdapterHolder.TYPE_ADD_PERSON}, this, UserListChosenActivity.class, ADD_MEMBER_CODE);
                break;

            case R.id.add_finished_button:
                String departName = departNameInput.getText().toString();
                if (TextUtils.isEmpty(departName)) {
                    shortToast(getString(R.string.department_name_is_none));
                    return;
                }
                if (mainManager == null) {
                    shortToast(getString(R.string.main_manager_is_none));
                    return;
                }
                List<PersonUserBean> sendJsonPersonBean = new ArrayList<>();
                for (PersonUserBean memberBean : memberList) {
                    sendJsonPersonBean.add(new PersonUserBean(memberBean.getUid(), ConstantsState.DEPARTMENT_NORMAL_POWER));
                }
                for (PersonUserBean manageBean : managerList)
                    sendJsonPersonBean.add(new PersonUserBean(manageBean.getUid(), ConstantsState.DEPARTMENT_VICE_MANAGER_POWER));

                Gson gson = new Gson();
                String personArrJson = gson.toJson(sendJsonPersonBean);
                NaizhuAILog.e("manageId=" +mainManager.getUid() );
                NaizhuAILog.e("gson.toJson(sendJsonPersonBean)=" + personArrJson);
                NaizhuAILog.e("departName=" + departName);
                Subscription createSub = CompanyManageDataApiStoreIml.getInstance().createTeam(departName, mainManager.getUid(), personArrJson).subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        ApiException.showException(e, getActivityContext(), true);
                    }

                    @Override
                    public void onNext(String s) {
                        hideWaitDialog();
                        if (ConstantsState.isResultOk(s)) {
                            shortToast(getString(R.string.department_create_ok));
                            IntentUtils.startActivity(CompanyAddPartActivity.this, CompanyTotalStructureActivity.class);
                        } else
                            shortToast(getString(R.string.department_create_no));
                    }
                });
                showWaitDiaLog(createSub);
                break;
            case R.id.chosen_main_manager:
                //添加主管理员
                IntentUtils.startActivityWithStringForResult(new String[]{ChosenChargeJoinAdapterHolder.ENTER_TYPE_KEY},
                        new int[]{ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_TEAM_MAIN_MANAGER}, this, UserListChosenActivity.class, ADD_MEMBER_MAIN);
                break;
        }
    }

    @Override
    public void onBackPressedWithoutDialog() {
        DialogUtils.showSureDialog(this, getString(R.string.lost_data), dialog -> finish());
    }

    @Override
    public void onItemClick(View view, int position, int listType) {
        PersonUserEditBean userEditBean = new PersonUserEditBean();
        switch (listType) {
            case AddTeamAdapterHolder.LIST_TYPE_MANAGE:
                userEditBean.setPersonBean(managerList.get(position));
                userEditBean.setBeDepartPowerCode(ConstantsState.DEPARTMENT_VICE_MANAGER_POWER);
                userEditBean.setBeDepartPowerMsg(ConstantsState.DEPARTMENT_VICE_MANAGER_POWER_STRING);
                break;
            case AddTeamAdapterHolder.LIST_TYPE_MEMBER:
                userEditBean.setPersonBean(memberList.get(position));
                userEditBean.setBeDepartPowerCode(ConstantsState.DEPARTMENT_NORMAL_POWER);
                userEditBean.setBeDepartPowerMsg(ConstantsState.DEPARTMENT_NORMAL_POWER_STRING);
                break;
        }
        IntentUtils.startActivityWithObjectAndStringForResult(PersonUserBean.USER_KEY, userEditBean,
                CompanyUseOperatActivity.ENTER_TYPE_KEY, CompanyUseOperatActivity.ENTER_FROM_ADD, this, CompanyUseOperatActivity.class, CLICK_OPERATE_CODE);
    }

}
